# Copyright 2008 Google Inc.
#coding=utf-8
import os

from google.appengine.api import users
from google.appengine.ext import db
from google.appengine.ext.db import djangoforms

import django
from django import http

from seblog.web.render import render_to_response

class Friend(db.Model):
    name = db.StringProperty()
    msn = db.StringProperty()
    created = db.DateTimeProperty(auto_now_add=True)
    modified = db.DateTimeProperty(auto_now=True)

def respond(request, template, params=None):
    if params is None:
        params = {}

    if not template.endswith('.html'):
        template += '.html'
    template = 'demoapp/update_ajax/' + template
    return render_to_response(template, params)

def index(request):
    friends = db.GqlQuery('SELECT * FROM Friend ORDER BY created DESC')
    return respond(request, 'list', {'friends': friends})

def new(request):
    return edit(request, None)

def edit(request, friend_id=None):
    friend = None
    if friend_id:
        friend = Friend.get_by_id(int(friend_id))
#        friend = Friend.get(db.Key.from_path('Friend', int(friend_id)))
        if friend is None:
            return http.HttpResponseNotFound('No friend exists with that key (%r)' %
                                       friend_id)
        return respond(request, 'friend', {'friend': friend})       
    else:
        return respond(request, 'friend')
    
def save(request):
    try:
        friend_id = request.POST.get('friend_id', None)
        if friend_id:
            friend = Friend.get_by_id(int(friend_id))
#            friend = Friend.get(db.Key.from_path(Friend.kind(), int(friend_id)))
        else:
            friend = Friend()
        name = unicode(request.POST['name'], 'UTF-8') 
        msn = unicode(request.POST['msn'], 'UTF-8') 
        friend.name = name
        friend.msn = msn
        friend.put()
#        print 'successful'#一有print，则下面的句子不转了，草
        return http.HttpResponse(u'true')
    except Exception,e:
        return http.HttpResponse(str(e))
